import logging
import yaml
from os import path


def log_save(name, context):
    """
    保存日志
    :param context: 日志内容
    :param name: 日志名称
    :return: 无
    """
    global logFile
    try:
        logFile = logging.FileHandler(dirname('log.txt', 'log'), 'a' , 'utf-8')
        fmt = logging.Formatter('%(asctime)s %(levelname)s——%(name)s: %(message)s')
        logFile.setFormatter(fmt)
        logger = logging.Logger(name, logging.DEBUG)
        logger.addHandler(logFile)
        logger.info(context)
    finally:
        logFile.close()

def dirname(filename='', filepath=''):
    """
    文件路径
    :param filename:
    :param filepath:
    :return:
    """
    return path.join(path.dirname(path.dirname(__file__)), filepath, filename)

def read_yaml(key, filepath = dirname('config.yaml', 'config')):
    with open(filepath, 'r', encoding='utf-8') as f:
        data = yaml.safe_load(f)
    if key in data:
        return data[key]
    else:
        log_save('数据错误', '配置文件中没有{}该元素'.format(key))
        return None

if __name__ == '__main__':
    print(read_yaml('gaode')['key'])